package com.hd.appcommon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hd.appcommon.entity.OrgMemberRole;
import com.hd.appcommon.mapper.OrgMemberRoleMapper;
import com.hd.appcommon.service.IOrgMemberRoleService;
import com.hd.hdxgddcommon.utils.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员关联角色 服务实现类
 * </p>
 *
 * @author administrator
 * @since 2020-11-30
 */
@Service
public class OrgMemberRoleServiceImpl extends ServiceImpl<OrgMemberRoleMapper, OrgMemberRole> implements IOrgMemberRoleService {

    @Override
    @CacheEvict(value = "RoleCache", key = "#p0")
    public boolean save(String orgMemberId, String[] roleIds) {
        LambdaQueryWrapper<OrgMemberRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgMemberRole::getOrgMemberId, orgMemberId);
        this.baseMapper.delete(wrapper);
        //roleIds为空则只清空集合
        if (roleIds == null || roleIds.length == 0) return true;
        List<OrgMemberRole> orgMemberRoles = Arrays.asList(roleIds).stream()
                //转换
                .map(roleId -> {
                    if (StringUtils.isBlank(roleId)) return null;
                    OrgMemberRole orgMemberRole = new OrgMemberRole();
                    orgMemberRole.setOrgMemberId(orgMemberId).setRoleId(roleId);
                    return orgMemberRole;
                })
                //去空
                .filter(f -> f != null)
                .collect(Collectors.toList());
        return this.saveBatch(orgMemberRoles);
    }

    @Override
    public boolean removeByOrgMemberId(String orgMemberId) {
        LambdaQueryWrapper<OrgMemberRole> lambda = new LambdaQueryWrapper<>();
        lambda.eq(OrgMemberRole::getOrgMemberId, orgMemberId);
        return this.remove(lambda);
    }

    @Override
    public boolean removeByRoleId(String roleId) {
        LambdaQueryWrapper<OrgMemberRole> lambda = new LambdaQueryWrapper<>();
        lambda.eq(OrgMemberRole::getRoleId, roleId);
        return this.remove(lambda);
    }
}
